<!-- 参考模板：https://codepen.io/ricardoolivaalonso/full/YzyaRPN -->
<!-- 参考教程：https://blog.csdn.net/Wind_AN/article/details/125539939 -->
<!-- 参考教程：https://blog.csdn.net/qq_41045128/article/details/125651144 -->
<template>
  <div class="body">
    <div class="main-box">
      <div :class="['container', 'container-register', { 'is-txl': isLogin }]">
        <form>
          <h2 class="title">注册</h2>
          <div class="form__icons">
            <img class="form__icon" src="https://aitravelhelper.oss-cn-guangzhou.aliyuncs.com/wechat.png" alt="微信登录">
            <img class="form__icon" src="https://aitravelhelper.oss-cn-guangzhou.aliyuncs.com/alipay.png" alt="支付宝登录">
            <img class="form__icon" src="https://aitravelhelper.oss-cn-guangzhou.aliyuncs.com/QQ.png" alt="QQ登录">
          </div>
          <span class="text">或使用邮箱进行注册</span>
          <input class="form__input" type="text" v-model="registerForm.email" placeholder="请输入邮箱"/>
          <div class="verify-code-group">
            <input class="form__input" type="text" v-model="registerForm.verifyCode" placeholder="请输入验证码" style="width: 220px;"/>
            <button
              type="button"
              class="verify-code-btn"
              @click="sendVerifyCode"
              :disabled="sendingCode || countdown > 0"
              :class="{ loading: sendingCode, disabled: countdown > 0 }"
            >
              <span v-if="sendingCode" class="spinner"></span>
              {{ sendingCode ? '发送中...' : (countdown > 0 ? `${countdown}秒后重试` : '发送验证码') }}
            </button>
          </div>
          <input class="form__input" type="password" v-model="registerForm.password" placeholder="请输入密码"/>
          <input class="form__input" type="password" v-model="registerForm.confirmPassword" placeholder="请确认密码"/>
          <div class="form__button" @click="register">立即注册</div>
        </form>
      </div>
      <div :class="['container', 'container-login', { 'is-txl is-z200': isLogin }]">
        <form>
          <h2 class="title">登录</h2>
          <div class="form__icons">
            <img class="form__icon" src="https://aitravelhelper.oss-cn-guangzhou.aliyuncs.com/wechat.png" alt="微信登录">
            <img class="form__icon" src="https://aitravelhelper.oss-cn-guangzhou.aliyuncs.com/alipay.png" alt="支付宝登录">
            <img class="form__icon" src="https://aitravelhelper.oss-cn-guangzhou.aliyuncs.com/QQ.png" alt="QQ登录">
          </div>
          <span class="text">或使用邮箱登录</span>
          <input class="form__input" type="text" v-model="loginForm.email" placeholder="请输入邮箱"/>
          <input class="form__input" type="password" v-model="loginForm.password" placeholder="请输入密码"/>
          <div class="form__button" @click="login">立即登录</div>
        </form>
      </div>
      <div :class="['switch', { 'login': isLogin }]">
        <div class="switch__circle"></div>
        <div class="switch__circle switch__circle_top"></div>
        <div class="switch__container">
          <h2>{{ isLogin ? '您好 !' : '欢迎回来 !' }}</h2>
          <p>
            {{
              isLogin
                  ? '如果您还没有账号，请点击下方立即注册按钮进行账号注册'
                  : '如果您已经注册过账号，请点击下方立即登录按钮进行登录'
            }}
          </p>
          <div class="form__button" @click="isLogin = !isLogin">
            {{ isLogin ? '立即注册' : '立即登录' }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { userApi, verifyCodeApi } from '@/utils/api';

// 定义组件名
defineOptions({
  name: 'LoginView'
});

const router = useRouter();

// 响应式数据
const isLogin = ref(true);

const loginForm = ref({
  email: '',
  password: '',
});

const registerForm = ref({
  email: '',
  verifyCode: '',
  password: '',
  confirmPassword: '',
});

// 倒计时
const countdown = ref(0);
let countdownTimer = null;
const sendingCode = ref(false);

// 提示方法
const showToast = (message) => {
  // 简单的提示实现，你可以根据需要替换为更完善的提示组件
  console.log('提示:', message);
  alert(message);
};

// 发送验证码
const sendVerifyCode = async () => {
  // 验证邮箱
  if (!registerForm.value.email) {
    showToast('请先输入邮箱');
    return;
  }

  // 邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(registerForm.value.email)) {
    showToast('请输入正确的邮箱格式');
    return;
  }

  try {
    sendingCode.value = true;
    await verifyCodeApi.sendVerifyCode(registerForm.value.email);
    showToast('验证码已发送，请查收');

    // 开始倒计时（5分钟 = 300秒）
    countdown.value = 300;
    countdownTimer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(countdownTimer);
      }
    }, 1000);
  } catch (error) {
    showToast(error.message || '验证码发送失败');
  } finally {
    sendingCode.value = false;
  }
};

// 登录方法
const login = async () => {
  // 表单验证
  if (!loginForm.value.email || !loginForm.value.password) {
    showToast('请输入邮箱和密码');
    return;
  }

  try {
    const res = await userApi.login(loginForm.value.email, loginForm.value.password);

    console.log('登录响应:', res);

    if (res.code === 200) {
      // 保存用户信息到本地存储
      if (res.data) {
        localStorage.setItem('userInfo', JSON.stringify(res.data.user));

        // 获取token
        const token = res.data.token;

        if (token) {
          localStorage.setItem('token', token);
        }
      }

      // 先显示成功提示
      showToast(res.message || '登录成功');

      // 延迟跳转到聊天页面
      setTimeout(() => {
        router.push('/chat');
      }, 1000);
    } else {

      showToast(res?.message || '登录失败，请重试');
    }
  } catch (error) {
    console.error('登录错误:', error);
    showToast(error?.message || error?.toString() || '登录失败，请重试');
  }
};

// 注册方法
const register = async () => {
  // 表单验证
  if (!registerForm.value.email || !registerForm.value.password || !registerForm.value.confirmPassword) {
    showToast('请填写完整信息');
    return;
  }

  if (!registerForm.value.verifyCode) {
    showToast('请输入验证码');
    return;
  }

  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    showToast('两次密码输入不一致');
    return;
  }

  try {
    // 先验证验证码
    const verifyRes = await verifyCodeApi.verifyCode(registerForm.value.email, registerForm.value.verifyCode);

    if (verifyRes.code !== 200) {
      showToast(verifyRes.message || '验证码错误');
      return;
    }

    // 验证码验证成功后，进行注册
    const res = await userApi.register(registerForm.value.email, registerForm.value.password);

    if (res.code === 200) {
      showToast(res.message || '注册成功');

      // 清除倒计时
      if (countdownTimer) {
        clearInterval(countdownTimer);
        countdown.value = 0;
      }

      // 延迟切换到登录页面
      setTimeout(() => {
        isLogin.value = true;
        registerForm.value = {
          email: '',
          verifyCode: '',
          password: '',
          confirmPassword: '',
        };
      }, 1000);
    } else if (res.code === 400) {
      showToast(res.message || '该邮箱已注册');
      return;
    } else {
      showToast(res.message || '注册失败，请重试');
      return;
    }
  } catch (error) {
    console.error('注册失败:', error);
    showToast(error.message || '注册失败，请重试');
  }
};
</script>

<style lang="scss" scoped>
.body {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: "Montserrat", sans-serif;
  font-size: 12px;
  background-image: url("https://aitravelhelper.oss-cn-guangzhou.aliyuncs.com/background.jpg");
  color: #a0a5a8;

}
.main-box {
  position: relative;
  width: 1000px;
  min-width: 1000px;
  min-height: 600px;
  height: 600px;
  padding: 25px;
  background-color: #ecf0f3;
  box-shadow: 1px 1px 100px 10PX #ecf0f3;
  border-radius: 12px;
  overflow: hidden;

  .container {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    width: 600px;
    height: 100%;
    padding: 25px;
    background-color: #ecf0f3;
    transition: all 1.25s;

    form {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      color: #a0a5a8;

      .form__icon {
        object-fit: contain;
        width: 30px;
        margin: 0 5px;
        opacity: .5;
        transition: .15s;

        &:hover {
          opacity: 1;
          transition: .15s;
          cursor: pointer;

        }
      }

      .title {
        font-size: 34px;
        font-weight: 700;
        line-height: 3;
        color: #181818;
      }

      .text {
        margin-top: 30px;
        margin-bottom: 12px;
      }

      .form__input {
        width: 350px;
        height: 40px;
        margin: 4px 0;
        padding-left: 25px;
        font-size: 13px;
        letter-spacing: 0.15px;
        border: none;
        outline: none;
        // font-family: 'Montserrat', sans-serif;
        background-color: #ecf0f3;
        transition: 0.25s ease;
        border-radius: 8px;
        box-shadow: inset 2px 2px 4px #d1d9e6, inset -2px -2px 4px #f9f9f9;

        &::placeholder {
          color: #a0a5a8;
        }
      }

      .verify-code-group {
        display: flex;
        gap: 10px;
        width: 350px;
        justify-content: space-between;
        align-items: center;

        .verify-code-btn {
          width: 120px;
          height: 40px;
          border: none;
          outline: none;
          font-size: 12px;
          letter-spacing: 0.5px;
          background-color: #4b70e2;
          color: #f9f9f9;
          cursor: pointer;
          border-radius: 8px;
          box-shadow: 4px 4px 8px #d1d9e6, -4px -4px 8px #f9f9f9;
          transition: 0.25s ease;

          &:hover:not(:disabled) {
            box-shadow: 2px 2px 4px #d1d9e6, -2px -2px 4px #f9f9f9;
          }

          &.disabled,
          &:disabled {
            background-color: #a0a5a8;
            cursor: not-allowed;
            opacity: 0.6;
          }

          &.loading {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
          }

          .spinner {
            width: 14px;
            height: 14px;
            border: 2px solid rgba(255,255,255,.4);
            border-top-color: #fff;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
          }
        }
      }
    }
  }

  @keyframes spin {
    to { transform: rotate(360deg); }
  }

  .container-register {
    z-index: 100;
    left: calc(100% - 600px);
  }

  .container-login {
    left: calc(100% - 600px);
    z-index: 0;
  }

  .is-txl {
    left: 0;
    transition: 1.25s;
    transform-origin: right;
  }

  .is-z200 {
    z-index: 200;
    transition: 1.25s;
  }

  .switch {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 400px;
    padding: 50px;
    z-index: 200;
    transition: 1.25s;
    background-color: #ecf0f3;
    overflow: hidden;
    box-shadow: 4px 4px 10px #d1d9e6, -4px -4px 10px #f9f9f9;
    color: #a0a5a8;

    .switch__circle {
      position: absolute;
      width: 500px;
      height: 500px;
      border-radius: 50%;
      background-color: #ecf0f3;
      box-shadow: inset 8px 8px 12px #d1d9e6, inset -8px -8px 12px #f9f9f9;
      bottom: -60%;
      left: -60%;
      transition: 1.25s;
    }

    .switch__circle_top {
      top: -30%;
      left: 60%;
      width: 300px;
      height: 300px;
    }

    .switch__container {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      position: absolute;
      width: 400px;
      padding: 50px 55px;
      transition: 1.25s;

      h2 {
        font-size: 34px;
        font-weight: 700;
        line-height: 3;
        color: #181818;
      }

      p {
        font-size: 14px;
        letter-spacing: 0.25px;
        text-align: center;
        line-height: 1.6;
      }
    }
  }

  .login {
    left: calc(100% - 400px);

    .switch__circle {
      left: 0;
    }
  }

  .form__button {
    width: 180px;
    height: 50px;
    border-radius: 25px;
    margin-top: 50px;
    text-align: center;
    line-height: 50px;
    font-size: 14px;
    letter-spacing: 2px;
    background-color: #4b70e2;
    color: #f9f9f9;
    cursor: pointer;
    box-shadow: 8px 8px 16px #d1d9e6, -8px -8px 16px #f9f9f9;

    &:hover {
      box-shadow: 2px 2px 3px 0 rgba(255, 255, 255, 50%),
      -2px -2px 3px 0 rgba(116, 125, 136, 50%),
      inset -2px -2px 3px 0 rgba(255, 255, 255, 20%),
      inset 2px 2px 3px 0 rgba(0, 0, 0, 30%);
    }
  }
}
</style>

